package com.wjbgn.util.threadpool;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @description： 全局线程池守护进程
 * @author：weirx
 * @date：2021/9/10 16:32
 * @version：3.0
 */
@Slf4j
//@Component
public class DaemonThreadTask {

    /**
     * 服务支持最大线程数
     */
    public final static int SERVER_MAX_SIZE = 50;

    /**
     * 最大阈值Maximum threshold，百分比
     */
    private final static int MAXIMUM_THRESHOLD = 8;

    /**
     * 每次递增最大线程数
     */
    private final static int INCREMENTAL_MAX_NUM = 10;

    /**
     * 每次递增核心线程数
     */
    private final static int INCREMENTAL_CORE_NUM = 5;

    /**
     * 当前线程数
     */
    private static int currentSize = GlobalThreadPool.MAX_NUM_POOL_SIZE;

    /**
     * 当前核心线程数
     */
    private static int currentCoreSize = GlobalThreadPool.CORE_POOL_SIZE;

    @Scheduled(cron = "0 */5 * * * ?")
    public static void execute() {
        threadMonitor();
    }


    /**
     * description: 动态监控并设置线程参数
     *
     * @return: void
     * @author: weirx
     * @time: 2021/9/10 13:20
     */
    private static void threadMonitor() {
        ThreadPoolExecutor instance = GlobalThreadPool.getExecutor();
        int activeCount = instance.getActiveCount();
        int size = instance.getQueue().size();
        log.info("GlobalThreadPool: the active thread count is {}", activeCount);
        // 线程数不足，增加线程
        if (activeCount > GlobalThreadPool.MAX_NUM_POOL_SIZE % MAXIMUM_THRESHOLD
                && size >= GlobalThreadPool.BLOCKING_QUEUE_SIZE) {
            currentSize = currentSize + INCREMENTAL_MAX_NUM;
            currentCoreSize = currentCoreSize + INCREMENTAL_CORE_NUM;
            //当前设置最大线程数小于服务最大支持线程数才可以继续增加线程
            if (currentSize <= SERVER_MAX_SIZE) {
                instance.setMaximumPoolSize(currentSize);
                instance.setCorePoolSize(currentCoreSize);
                log.info("this max thread size is {}", currentSize);
            } else {
                log.info("current size is more than server max size, can not add");
            }
        }
        // 线程数足够，降低线程数，当前活跃数小于默认核心线程数
        if (activeCount < GlobalThreadPool.MAX_NUM_POOL_SIZE
                && size == 0
                && currentSize > GlobalThreadPool.MAX_NUM_POOL_SIZE) {
            currentSize = GlobalThreadPool.MAX_NUM_POOL_SIZE;
            currentCoreSize = GlobalThreadPool.CORE_POOL_SIZE;
            instance.setMaximumPoolSize(currentSize);
            instance.setCorePoolSize(currentCoreSize);
        }
    }
}
